﻿using SingletonSean.ViewModels;

namespace SingletonSean
{
    public class NavigationService
    {
        //本案例是使用IOC将NavigationService注册为单例，也可以手动实现
        //public static NavigationService Instance  {get;} = new NavigationService();
        //private NavigationService() { }
        private ViewModelBase? currentViewModel;
        public ViewModelBase? CurrentViewModel
        {
            get => currentViewModel;
            set
            {
                currentViewModel = value;
                // 每次属性改变即导航的时候都会执行这个事件
                // 我们在MainVM中实例化事件(将需要导航的PageVM传递给MainVW)
                CurrentViewModelChanged?.Invoke();
            }
        }
        public event Action? CurrentViewModelChanged;
        public void NavigateTo<T>() where T : ViewModelBase
            => CurrentViewModel = App.Current.Services.GetService<T>();
        // 添加支持传递参数的导航方法
        public void NavigateTo<T>(Action<T> parameterAction) where T : ViewModelBase
        {
            var viewModel = App.Current.Services.GetService<T>();
            if (viewModel != null)
            {
                // 在设置当前ViewModel之前应用参数
                parameterAction(viewModel);
                CurrentViewModel = viewModel;
            }
        }
    }
}
